package com.useeinfo.oa.open.admin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.data.SelectVO;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.FacilityBiz;
import com.useeinfo.oa.modules.base.biz.FacilityCatBiz;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.base.entity.Facility;
import com.useeinfo.oa.modules.base.entity.FacilityCat;
import com.useeinfo.oa.modules.base.entity.Organization;
import com.useeinfo.oa.modules.logger.biz.FacilityCatLogBiz;
import com.useeinfo.oa.modules.logger.entity.FacilityCatLog;
import com.useeinfo.oa.modules.logger.enums.LogTypeEnum;
import com.useeinfo.oa.modules.security.biz.SystemUserBiz;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: bin.liu
 * @Date: 2018/12/5 16:03
 * @Description: 设备分类action
 */
@Controller
@RequestMapping("/web/admin/facilityCat")
public class FacilityCatManageAction {
    private final static Logger logger = LoggerFactory.getLogger(FacilityCatManageAction.class);
    @Autowired
    private FacilityCatBiz facilityCatBiz;
    @Autowired
    private FacilityBiz facilityBiz;
    @Autowired
    private SystemUserBiz systemUserBiz;
    @Autowired
    private FacilityCatLogBiz facilityCatLogBiz;

    @RequestMapping("/list")
    public ModelAndView list() {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/admin/facility/facilityCatList");

        return modelAndView;
    }

    @RequestMapping("/listJson")
    @ResponseBody
    public JSONObject listJson(@RequestParam(value = "pageNo", required = false) String pageNowParam,
                               @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                               @RequestParam(value = "searchCode", required = false) String searchCode,
                               @RequestParam(value = "parentCode", required = false) String parentCode,//tree参数
                               @RequestParam(value = "orderBy", required = false) String orderBy,
                               HttpServletRequest request) {
        JSONObject result = new JSONObject();
        QueryParam queryParam = new QueryParam(pageNowParam, pageSizeParam);
        queryParam.getSqlMap().put("searchCode", searchCode);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise!=null){
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId()+"");
        }
        if(StringUtils.isNotBlank(parentCode)){
            queryParam.getSqlMap().put("parentId", parentCode);
        }else{
            queryParam.getSqlMap().put("bigParent","0");
        }
        if(StringUtils.isNotBlank(orderBy)) {
            queryParam.setSqlOrder("order by " + orderBy);
        }
        result = facilityCatBiz.findJSONList(queryParam);
        JSONArray rows = result.getJSONArray("list");
        for (int i = 0; i < rows.size(); i++) {
            JSONObject json = rows.getJSONObject(i);
            //查出tree展示参数
            json.put("treeLevel",json.getInteger("lvl")==null?0:json.getIntValue("lvl"));
            json.put("isTreeLeaf",!facilityCatBiz.existHaveSon(json.getLong("id")));
            json.put("parentCode",json.getInteger("parentId")+"");//不加这个parentCode展开后就会缩不回去
            json.put("isRoot",true);
        }
        return result;
    }

    @RequestMapping("/editPage")
    public ModelAndView editPage(@RequestParam(value = "id", required = false) String id,HttpServletRequest request) {

        ModelAndView modelAndView = new ModelAndView();
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        modelAndView.addObject("enterprise",enterprise);
        FacilityCat facilityCat = facilityCatBiz.findModel(StringConverters.ToLong(id));
        modelAndView.addObject("facilityCat",facilityCat);
        modelAndView.setViewName("pages/admin/facility/facilityCatEdit");

        return modelAndView;
    }

    @RequestMapping("/addOrUpdate")
    @ResponseBody
    public ResultDto addOrUpdate(FacilityCat facilityCat) {
        facilityCatBiz.addOrUpdate(facilityCat);
        return ResultUtil.success();
    }

    /**
     * 执行提交的新增或修改请求
     */
    @RequestMapping("/executeFacilityCatEdit")
    @ResponseBody
    public ResultDto executeFacilityCatEdit(FacilityCat facilityCat,HttpServletRequest request,
                                            @RequestParam(value = "selectParentId[]", required = false) List<String> selectParentIds) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise==null){
            return ResultUtil.error("获取企业失败，请更新页面重试");
        }
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        if(systemUser==null){
            return ResultUtil.error("获取用户信息失败，请更新页面重试");
        }
        if (facilityCatBiz.existFacilityCatName(facilityCat,selectParentIds,enterprise.getId())) {
            return ResultUtil.error("您输入的类型名称为空或同专业下已存在，请重新输入");
        }
        if(CollectionUtils.isNotEmpty(selectParentIds)){
            if(facilityCat.getId()!=null&&facilityCat.getId().equals(StringConverters.ToLong(selectParentIds.get(0)))){
                return ResultUtil.error("您不能设置自己为上级，请重新输入");
            }
            FacilityCat parentCat = facilityCatBiz.findModel(StringConverters.ToLong(selectParentIds.get(0)));
            if(parentCat!=null){
                //先判断是否存在悖论关系
                if(facilityCat.getId()!=null&&StringUtils.isNotBlank(parentCat.getParentIds())&&parentCat.getParentIds().contains(facilityCat.getId()+"")){
                    return ResultUtil.error("您不能设置此上级类型，请重新输入");
                }

                facilityCat.setParentId(parentCat.getId());
                facilityCat.setLvl((parentCat.getLvl()!=null?parentCat.getLvl():0)+1);
                facilityCat.setParentIds((StringUtils.isEmpty(parentCat.getParentIds())?"":(parentCat.getParentIds()+","))+parentCat.getId());
            }else{
                facilityCat.setLvl(0);
                facilityCat.setParentIds("");
            }
        }else{
            facilityCat.setLvl(0);
            facilityCat.setParentIds("");
        }
        facilityCat.setEnterprise(enterprise);
        facilityCat.setSystemUserId(systemUser.getId());
        facilityCat.setSystemUserName(systemUser.getUserName());
        //添加日志
        FacilityCatLog facilityCatLog = new FacilityCatLog();
        if (facilityCat.getId() == null) {
            facilityCatLog.setLogTypeEnum(LogTypeEnum.insert);
        } else {
            facilityCatLog.setLogTypeEnum(LogTypeEnum.update);
        }
        facilityCatLog.setUserName(systemUser.getUserName());
        facilityCatLog.setUserId(systemUser.getId());
        facilityCatBiz.addOrUpdate(facilityCat);
        facilityCatLog.setFacilityCatId(facilityCat.getId());
        facilityCatLogBiz.addOrUpdate(facilityCatLog);
        //如果是变更上级 则整个下级团队都需要变更parentIds 以及 层级字段
        facilityCatBiz.recursionChangeParentIds(facilityCat.getId());
        return ResultUtil.success();
    }

    /**
     * 获取系统模块选择数据
     *
     * @param q
     * @return
     */
    @RequestMapping("/getFacilityCatSelect")
    @ResponseBody
    public JSONArray getFacilityCatSelect(@RequestParam(value = "q", required = false) String q,
                                          @RequestParam(value = "parentCatId", required = false) String parentCatId,
                                          @RequestParam(value = "id", required = false) String id,
                                          HttpServletRequest request) {
        //下面保证默认选择项加载正常
        String index = "";
        boolean status = false;//表示默认list中无此id的数据
        FacilityCat facilityCat = facilityCatBiz.findModel(StringConverters.ToLong(id));
        if(StringUtils.isBlank(q)&&facilityCat!=null){
            index = id;
        }
        JSONArray result = new JSONArray();
        List<SelectVO> selectVOS = new ArrayList<>();
        QueryParam queryParam = new QueryParam(1, 20);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise!=null){
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId()+"");
        }
        queryParam.getSqlMap().put("searchCode", q);
        if(StringUtils.isNotBlank(parentCatId)){
            if("0".equals(parentCatId)){
                queryParam.getSqlMap().put("bigParent", "随便写什么");
            }else{
                queryParam.getSqlMap().put("rootParentId", parentCatId);
            }
        }

        List<FacilityCat> facilityCatList = facilityCatBiz.findList(queryParam);
        facilityCatList.forEach(module -> selectVOS.add(new SelectVO(module.getCatName(), module.getId() + "")));
        for(SelectVO selectVO : selectVOS){
            if(StringUtils.isNotBlank(index)&&index.equals(selectVO.getValue())){
                status = true;
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("value",selectVO.getValue());
            jsonObject.put("text",selectVO.getText());
            result.add(jsonObject);
        }

        if(!status&&facilityCat!=null){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("value",facilityCat.getId()+"");
            jsonObject.put("text",facilityCat.getCatName());
            result.add(jsonObject);
        }
        return result;
    }

    /**
     * 逻辑删除机构用户信息
     */
    @RequestMapping("/logicRemoveFacilityCat")
    @ResponseBody
    public ResultDto logicRemoveFacilityCat(@RequestParam(value = "id", required = false) String idParam,
                                            HttpServletRequest request) {

        FacilityCat facilityCat = facilityCatBiz.findModel(StringConverters.ToLong(idParam));
        if(facilityCat==null){
            return ResultUtil.success();
        }
        //查出需要一起删除的下级（包括自己）list
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("ancestryId",idParam);
        List<FacilityCat> catList = facilityCatBiz.findList(queryParam);
        catList.add(facilityCat);
        //循环这个list 如果关联了设备 则不可以删除
        boolean status = false;
        for(FacilityCat cat : catList){
            QueryParam queryParam1 = new QueryParam();
            queryParam1.getSqlMap().put("facilityCatId",cat.getId()+"");
            List<Facility> facilityList = facilityBiz.findList(queryParam1);
            if(CollectionUtils.isNotEmpty(facilityList)){
                status = true;
                break;
            }
        }
        if(status){
            return ResultUtil.error("已关联设备,无法删除!");
        }
        //循环删除
        for(FacilityCat cat : catList){
            facilityCatBiz.deleteLogic(cat);
        }
        //添加日志
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        FacilityCatLog facilityCatLog = new FacilityCatLog();
        facilityCatLog.setLogTypeEnum(LogTypeEnum.delete);
        facilityCatLog.setUserName(systemUser.getUserName());
        facilityCatLog.setUserId(systemUser.getId());
        facilityCatLog.setFacilityCatId(facilityCat.getId());
        facilityCatLogBiz.addOrUpdate(facilityCatLog);
        return ResultUtil.success();
    }

    /**
     * 获取部门-选择框
     */
    @RequestMapping("/getFacilityCatListMagic")
    @ResponseBody
    public List<SelectVO> getFacilityCatListMagic(@RequestParam(value = "q", required = false) String q,
                                                   @RequestParam(value = "id", required = false) String id,HttpServletRequest request) {
        //下面保证默认选择项加载正常
        String index = "";
        boolean status = false;//表示默认list中无此id的数据
        FacilityCat facilityCat = facilityCatBiz.findModel(StringConverters.ToLong(id));
        if(StringUtils.isBlank(q)&&facilityCat!=null){
            index = id;
        }
        List<SelectVO> selectVOS = new ArrayList<>();
        Enterprise enterprise=SessionKeyUtils.getSessionEnterprise(request);
        QueryParam queryParam = new QueryParam(1, 20);
        queryParam.getSqlMap().put("magicLike", q);
        queryParam.getSqlMap().put("magicId", id);
        queryParam.getSqlMap().put("enterpriseId", enterprise.getId()+"");
        List<FacilityCat> facilityCats = facilityCatBiz.findList(queryParam);
        if(CollectionUtils.isNotEmpty(facilityCats)){
            for(FacilityCat facilityCat1 : facilityCats){
                if(StringUtils.isNotBlank(index)&&index.equals(facilityCat1.getId()+"")){
                    status = true;
                }
                selectVOS.add(new SelectVO(facilityCat1.getCatName(), facilityCat1.getId() + ""));
            }
        }
        if(!status&&facilityCat!=null){
            selectVOS.add(new SelectVO(facilityCat.getCatName(), facilityCat.getId() + ""));
        }
        return selectVOS;
    }
    /**
     * 获取专业
     */
    @RequestMapping("/getRootCatNameById")
    @ResponseBody
    public ResultDto getRootCatNameById(@RequestParam(value = "id", required = false) String id,
                                            HttpServletRequest request) {
        FacilityCat facilityCat=facilityCatBiz.findModel(StringConverters.null2Long(id));
        return ResultUtil.success(facilityCat.getCatName());
    }
}
